#include <pthread.h>

#include "report.h"
int flag = 0;
static struct shm_param para;

MQTTClient client;
struct std_node *addr;            // 存放共享内存的地址
struct mqtt data;                 // ip和port等信息
int *total_num_ptr = NULL;        // 指向前四个字节的总数
struct std_node *data_ptr = NULL; // 指向四个字节后的第一个结构体
char *errmsg;
sqlite3 *db;

void *DatabaseSave(void *arg)
{
    int num = *total_num_ptr;
    struct std_node *tmp = data_ptr;

    char sql[128] = {0};

    char buf[32] = {0};

    time_t timep;

    while (1)
    {
        LOGD("存储到数据库\n");
        for (int i = 0; i < num; i++)
        {
            switch (tmp[i].type)
            {
            case 1:
                sprintf(buf, "%d", tmp[i].new_val.b_val);
                tmp[i].old_val.b_val = tmp[i].new_val.b_val;
                break;
            case 2:
                sprintf(buf, "%d", tmp[i].new_val.i_val);
                tmp[i].old_val.i_val = tmp[i].new_val.i_val;
                break;
            case 3:
                sprintf(buf, "%.2f", tmp[i].new_val.f_val);
                tmp[i].old_val.f_val = tmp[i].new_val.f_val;
                break;
            default:
                break;
            }
            time(&timep);
            sprintf(sql, "insert into mydata values(\"%ld\",\"%d\",\"%s\");", timep, tmp[i].key, buf);
            if (sqlite3_exec(db, sql, NULL, NULL, &errmsg) != 0)
            {
                fprintf(stderr, "insert err:%s\n", errmsg);
            }
        }
        sleep(60);
    }
}

int main(int argc, char const *argv[])
{
    set_dbg_level(APP_DEBUG);

    json_init(&data);

    struct std_node *shm1 = myshm_init(&para, "shm_stm32", 1024);
    if (shm1 == NULL)
    {
        perror("myshm_init err");
        return -1;
    }
    struct std_node *shm2 = myshm_init(&para, "shm_modbus", 1024);
    if (shm2 == NULL)
    {
        perror("myshm_init err");
        return -1;
    }
    LOGD("shm1 shm2 init success");
    struct std_node *all[2] = {shm1, shm2};

    addr = shm_getaddr(&para);
    if (addr == NULL)
    {
        LOGE("共享内存映射失败");
        return -1;
    }
    // 给总数地址和结构体的地址
    total_num_ptr = (int *)addr;
    data_ptr = (int *)addr + 1;
    *total_num_ptr = 0;
    // 初始化数据库
    create_database();
    pthread_t tid;
    if (pthread_create(&tid, NULL, DatabaseSave, NULL) != 0)
    {
        LOGE("pthread_create error\n");
    }
    LOGD("pthread create success\n");
    char ADDRESS[50];
    sprintf(ADDRESS, "tcp://%s:%d", data.ip, data.port);

    printf("ADDRESS:%s\n", ADDRESS);
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    int rc;
    // int ch;
    MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);

    MQTTClient_message pubmsg = MQTTClient_message_initializer;
    MQTTClient_deliveryToken token;
    UNUSED(pubmsg);
    UNUSED(token);
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;
    MQTTClient_setCallbacks(client, &client, connlost, msgarrvd, delivered);
    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to connect, return code %d\n", rc);
        exit(EXIT_FAILURE);
    }

    MQTTClient_subscribe(client, RECVDATATOPIC, QOS);

    printf("ip=%s,port=%d,type=%d,period=%d\n", data.ip, data.port, data.type, data.period);

    switch (data.type)
    {
    case 0:
        // refresh_report(client, all);
        sleep(2000);
        break;
    case 1:
        change_report(client, all);
        break;
    case 2:
        period_report(client, all, data.period);
        break;
    default:
        break;
    }

    MQTTClient_unsubscribe(client, RECVDATATOPIC);
    MQTTClient_disconnect(client, 10000);
    MQTTClient_destroy(&client);
    sqlite3_close(db);
    // shm_del(&para);
    // pthread_join(tid,NULL);
    return 0;
}
